package com.example.myframe.able;

import android.text.Editable;
import android.text.TextWatcher;
import com.blankj.utilcode.constant.RegexConstants;
import com.blankj.utilcode.util.RegexUtils;
import com.a.lib_bean.enums.TextType;

/**
 * CREATE BY 黄炜强
 * 2022-7-10
 * Desc:用于处理数字
 */
public abstract class NumberTextWatcher implements TextWatcher {
    private final TextType type;

    /**
     * 判断输入内容是否为数字
     *
     * @param type 需要判断数字类型
     */
    public NumberTextWatcher(TextType type) {
        this.type = type;
    }

    /**
     * @param isMatch 判断是否匹配
     */
    public abstract void textChanged(CharSequence s, int start, int before, int count, boolean isMatch);

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s.length() == 0) {
            textChanged("0", start, before, count, true);
            return;
        }
        if (type == TextType.FLOAT) {
            if (RegexUtils.isMatch(RegexConstants.REGEX_FLOAT, s) || RegexUtils.isMatch(RegexConstants.REGEX_INTEGER, s)) {
                textChanged(s, start, before, count, true);
            }else {
                textChanged(s.subSequence(0, start), start, before, count, false);
            }
        } else if (type == TextType.INT) {
            if (RegexUtils.isMatch(RegexConstants.REGEX_INTEGER, s)) {
                textChanged(s, start, before, count, true);
            }else {
                textChanged(s.subSequence(0, start), start, before, count, false);
            }
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
